"""
系统安装验证脚本
验证所有核心组件是否正确安装和配置
"""

import sys
import yaml


def verify_dependencies():
    """验证依赖包是否正确安装"""
    print("=" * 60)
    print("步骤 1: 验证依赖包")
    print("=" * 60)

    dependencies = {
        'numpy': 'numpy',
        'opencv-python': 'cv2',
        'pandas': 'pandas',
        'scipy': 'scipy',
        'mediapipe': 'mediapipe',
        'torch': 'torch',
        'torchvision': 'torchvision',
        'transformers': 'transformers',
        'flask': 'flask',
        'flask-cors': 'flask_cors',
        'pyyaml': 'yaml',
        'pillow': 'PIL',
        'jinja2': 'jinja2',
        'matplotlib': 'matplotlib',
        'plotly': 'plotly',
        'pytest': 'pytest',
        'tqdm': 'tqdm',
        'python-dotenv': 'dotenv'
    }

    missing = []
    for name, module in dependencies.items():
        try:
            __import__(module)
            print(f"✓ {name}")
        except ImportError:
            print(f"✗ {name} - 未安装")
            missing.append(name)

    # Check soft-dtw separately (CUDA version not needed on macOS)
    print()
    print("检查Soft-DTW:")
    try:
        from soft_dtw_cuda import SoftDTW
        print("  ✓ soft-dtw-cuda (CUDA加速版)")
    except ImportError:
        print("  ℹ  soft-dtw-cuda不可用 (macOS预期行为)")
        print("  → 系统将使用CPU版回退实现")

    print()
    if missing:
        print(f"⚠️  缺失依赖: {', '.join(missing)}")
        return False
    else:
        print("✓ 所有必需依赖包已安装")
        return True


def verify_pytorch_mps():
    """验证PyTorch和MPS设备支持"""
    print("=" * 60)
    print("步骤 2: 验证PyTorch和MPS设备")
    print("=" * 60)

    import torch

    print(f"PyTorch版本: {torch.__version__}")
    print(f"MPS可用: {torch.backends.mps.is_available()}")
    print(f"MPS内置: {torch.backends.mps.is_built()}")

    if torch.backends.mps.is_available():
        print("✓ MPS设备支持正常 (Apple M4 GPU加速可用)")
        return True
    else:
        print("⚠️  MPS不可用，将使用CPU")
        return False


def verify_dinov2_model():
    """验证DINOv2模型加载"""
    print("=" * 60)
    print("步骤 3: 验证DINOv2模型")
    print("=" * 60)

    try:
        from transformers import AutoImageProcessor, AutoModel
        import torch

        model_name = 'facebook/dinov2-base'
        print(f"加载模型: {model_name}")

        processor = AutoImageProcessor.from_pretrained(model_name)
        print("✓ ImageProcessor加载成功")

        model = AutoModel.from_pretrained(model_name)
        print("✓ Model加载成功")

        # 尝试移至MPS设备
        if torch.backends.mps.is_available():
            device = torch.device('mps')
            model = model.to(device)
            print(f"✓ 模型已移至MPS设备")
        else:
            print("  使用CPU设备")

        print(f"特征维度: {model.config.hidden_size}")
        print(f"模型类型: {type(model).__name__}")
        print()
        print("✓ DINOv2模型验证成功")
        return True

    except Exception as e:
        print(f"✗ DINOv2模型加载失败: {e}")
        return False


def verify_core_modules():
    """验证核心模块是否可导入"""
    print("=" * 60)
    print("步骤 4: 验证核心模块")
    print("=" * 60)

    modules = [
        'src.core.pose_detector',
        'src.core.skeleton_normalizer',
        'src.core.feature_extractor',
        'src.core.action_segmenter',
        'src.core.matcher',
        'src.core.report_generator',
        'src.utils.template_builder'
    ]

    failed = []
    for module_name in modules:
        try:
            __import__(module_name)
            print(f"✓ {module_name}")
        except Exception as e:
            print(f"✗ {module_name}: {e}")
            failed.append(module_name)

    print()
    if failed:
        print(f"⚠️  模块导入失败: {', '.join(failed)}")
        return False
    else:
        print("✓ 所有核心模块可正常导入")
        return True


def verify_config():
    """验证配置文件"""
    print("=" * 60)
    print("步骤 5: 验证配置文件")
    print("=" * 60)

    try:
        with open('config.yaml', 'r') as f:
            config = yaml.safe_load(f)

        print(f"✓ 配置文件加载成功")
        print(f"  - 模板目录: {config['paths']['templates']}")
        print(f"  - 特征提取模型: {config['feature_extraction']['model_name']}")
        print(f"  - 计算设备: {config['feature_extraction']['device']}")
        print(f"  - 特征维度: {config['feature_extraction']['feature_dim']}")
        print()
        print("✓ 配置验证成功")
        return True

    except Exception as e:
        print(f"✗ 配置文件验证失败: {e}")
        return False


def main():
    """运行所有验证"""
    print()
    print("康复动作评估系统 - 安装验证")
    print()

    results = []

    # 运行所有验证
    results.append(("依赖包", verify_dependencies()))
    results.append(("PyTorch/MPS", verify_pytorch_mps()))
    results.append(("DINOv2模型", verify_dinov2_model()))
    results.append(("核心模块", verify_core_modules()))
    results.append(("配置文件", verify_config()))

    # 总结
    print("=" * 60)
    print("验证总结")
    print("=" * 60)

    for name, success in results:
        status = "✓ 通过" if success else "✗ 失败"
        print(f"{name:20s} {status}")

    print()
    all_passed = all(result[1] for result in results)

    if all_passed:
        print("🎉 所有验证通过！系统已准备就绪。")
        print()
        print("下一步:")
        print("  1. 准备专家演示视频并构建模板")
        print("  2. 运行 'python example.py' 查看使用示例")
        print("  3. 启动API服务器: 'python src/api/app.py'")
        return 0
    else:
        print("⚠️  部分验证失败，请检查上述错误信息")
        return 1


if __name__ == '__main__':
    sys.exit(main())
